package com.rxy.config;

import com.rxy.pojo.Configuration;
import com.rxy.pojo.MapperStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class XMLMapperBuilder {

    private Configuration configuration;

    public  XMLMapperBuilder(Configuration configuration){
        this.configuration = configuration;
    }

    public void parse(InputStream in) throws DocumentException, ClassNotFoundException {
        Document document = new SAXReader().read(in);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        List<Element> list = new ArrayList<>();
        list.addAll(rootElement.selectNodes("//select"));
        list.addAll(rootElement.selectNodes("//update"));
        list.addAll(rootElement.selectNodes("//delete"));
        for (Element element : list) {
            String elemName = element.getName();
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramterType");
            String sqlText = element.getTextTrim();
            MapperStatement mapperStatement = new MapperStatement();
            mapperStatement.setSqlType(elemName);
            mapperStatement.setId(id);
            mapperStatement.setResultType(getClassType(resultType));
            mapperStatement.setParamterType(getClassType(paramterType));
            mapperStatement.setSql(sqlText);
            String key = namespace + "." + id;
            configuration.getMapperStatementMap().put(key, mapperStatement);
        }
    }

    private Class<?> getClassType(String paramterType) throws ClassNotFoundException {
        if(paramterType == null || "".equals(paramterType)){
            return null;
        }
        return Class.forName(paramterType);
    }
}
